package com.baselibrary.net.interceptor;

import android.content.Intent;

import com.baselibrary.MessageBus;
import com.baselibrary.utils.CommonUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnsupportedCharsetException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * @author zhanglijie
 * @date 20-3-10
 * @Description
 */
public class HttpStatusInterceptor implements Interceptor {
    private final Charset UTF8 = StandardCharsets.UTF_8;

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        //拦截http 401
        if (response.code() == 200) {
            // 2. 读 body 缓存到BufferedSource中
            ResponseBody responseBody = response.body();
            String jsonString = null;
            BufferedSource source = responseBody.source();
            // Buffer the entire body.
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.buffer();
            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                try {
                    charset = contentType.charset(UTF8);
                } catch (UnsupportedCharsetException e) {
                    e.printStackTrace();
                }
            }
            jsonString = buffer.clone().readString(charset);
            if (!CommonUtil.isBlank(jsonString)) {
                // 3. 转换 JSON ，读取 code 字段
                try {
                    JSONObject jsonObject = new JSONObject(jsonString);
                    boolean success = jsonObject.optBoolean("success");
                    int code = jsonObject.optInt("code");
                    if (code == 400 || code == 401) {
                        MessageBus.Builder builder = new MessageBus.Builder();
                        MessageBus messageBus = builder
                                .codeType(MessageBus.msgId_logout)
                                .message(code)
                                .build();
                        EventBus.getDefault().post(messageBus);
                    } else if (code == 404) {
                        Class mClass = null;
                        try {
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }


        }


        return response;
    }

}
